import axios from "axios";
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/el-message.css'
import { useUserStore } from '@/stores/userStore'
import { useRouter } from "vue-router";
import router from "@/router";
//接口
const httpInstance = axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
    timeout: 20000
})

//拦截器
httpInstance.interceptors.request.use(config => {
  //1.pinia里面获得token
  //2.按照后端的要求拼接token数据
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  if(token) {
    config.headers.Authorization = `Bearer ${token}`
  }
    return config
  }, e => Promise.reject(e))
  
  // axios响应式拦截器
httpInstance.interceptors.response.use(res => res.data, e => {
  
  //统一错误提示
  // console.log(e);
  
  ElMessage({
    type: 'warning',
    message: e.response.data.message
  })
  const userStore = useUserStore()
  //401token实效处理
  //1.清除本地用户数据
  if(e.request.status === 401) {
    userStore.clearUserInfo()
    router.push('/login')
  }
    return Promise.reject(e)
  })

  //2.跳转到登陆页面
export default httpInstance